package cn.sw.cloudmybatisplus.config;// src/main/java/cn/sw/cloudmybatisplus/config/BaseServicePostProcessor.java

import cn.sw.cloudmybatisplus.common.emun.BaseServiceOf;
import cn.sw.cloudmybatisplus.common.service.BaseService;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.core.GenericTypeResolver;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Map;

@Component
public class BaseServicePostProcessor implements BeanPostProcessor {

    @Autowired
    private ApplicationContext context;

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Class<?> beanClass = bean.getClass();

        // 判断是否标注了 @BaseServiceOf 注解
        if (beanClass.isAnnotationPresent(BaseServiceOf.class)) {
            BaseServiceOf annotation = beanClass.getAnnotation(BaseServiceOf.class);
            Class<?> entityClass = annotation.value();

            // 查找泛型为 entityClass 的 BaseService 实现

            Map<String, BaseService> services = context.getBeansOfType(BaseService.class);


            for (BaseService<?, ?, ?> service : services.values()) {
                Class<?>[] generics = GenericTypeResolver.resolveTypeArguments(service.getClass(), BaseService.class);
                if (generics != null && generics.length > 0 && generics[0].equals(entityClass)) {
                    // 找到匹配的 service，反射注入到 BaseController 的 baseService 字段
                    Field field = ReflectionUtils.findField(bean.getClass().getSuperclass(), "baseService");
                    if (field != null) {
                        ReflectionUtils.makeAccessible(field);
                        ReflectionUtils.setField(field, bean, service);
                    }
                }
            }
        }

        return bean;
    }
}
